package org.hyjiacan.deadqq.server.listener;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.hyjiacan.deadqq.common.entity.User;
import org.hyjiacan.deadqq.server.Server;
import org.hyjiacan.deadqq.server.dao.UserDAO;


public class RegistListener implements Runnable {

    private UserDAO ud;
    private ServerSocket socket;
    private BufferedReader br;
    private ObjectInputStream ois;
    private ObjectOutputStream oos;

    public RegistListener() {
        ud = new UserDAO();
    }

    /**
     * 注册一个新用户
     *
     * @return 若注册成功，返回用户注册获得的号码；否则返回-1
     */
    public long regist(User user) {
        long number = generateNumber();
        user.setNumber(number);
        while (!ud.add(user)) {
            number = generateNumber();
            user.setNumber(number);
        }
        return number;
    }

    private long generateNumber() {
        Random r = new Random(new Date().getTime());
        long number = Math.round(r.nextFloat() * 100000);
        return number;
    }

    @Override
    public void run() {
        while (true) {
            try {
                if (socket == null) {
                    socket = new ServerSocket(Server.REG_PORT);
                }
                System.out.println("开始监听注册");
                Socket s = socket.accept();
                ObjectInputStream ois;
                ois = new ObjectInputStream(s.getInputStream());
                User u = (User) ois.readObject();
                if (u.getNickname().isEmpty() || u.getPassword().isEmpty()) {
                    System.out.println("注册信息有误");
                    oos.writeLong(-1L);
                    oos.flush();
                    return;
                }
                System.out.println("收到注册信息：" + u.getNickname());
                oos = new ObjectOutputStream(s.getOutputStream());
                long number = regist(u);
                oos.writeLong(number);
                oos.flush();
                System.out.println("返回注册账号：" + number);

            } catch (java.net.BindException e) {
                System.err.println("端口" + Server.REG_PORT + "被占用");
            } catch (IOException ex) {
                Logger.getLogger(Server.class.getName()).log(Level.SEVERE,
                        null, ex);
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                try {
                    if (ois != null) {
                        ois.close();
                    }
                    if (br != null) {
                        br.close();
                    }
                } catch (IOException ex) {
                    Logger.getLogger(LoginListener.class.getName()).log(
                            Level.SEVERE, null, ex);
                }
            }
        }
    }
}
